/**
 * 
 */
package com.fc.remoting.logger;

import java.net.InetSocketAddress;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;

import com.alibaba.fastjson.JSONObject;
import com.fc.common.log.LoggingConfig;
import com.fc.remoting.message.RemotingMessage;

import io.netty.channel.AbstractChannel;
import io.netty.channel.Channel;

/**
 * 日记系统接入操作类
 * @author liangh
 *
 */
public class LogSystem {

	/**
	 * 
	 */
	private LogSystem(){}
	
	/**
	 * 单例
	 * @author liangh
	 *
	 */
	static class LogFactory{
		private static LogSystem logsystem = new LogSystem();
	}
	
	/**
	 * 单例
	 * @return 
	 */
	public static LogSystem instance(){
		return LogFactory.logsystem;
	}
	
	/** 线程变量，记录处理时间 **/
	private static ThreadLocal<Long>  currentThread = new ThreadLocal<Long>();
	
	/**
	 * 异步处理任务时记录任务开始
	 * @param log
	 * @param channel
	 * @param request
	 */
	public void protocolProcessBegin(Logger log,Channel channel, JSONObject request){
		try{	
			currentThread.set(System.currentTimeMillis());
			AbstractChannel achannel = (AbstractChannel)channel;
			String ip = ((InetSocketAddress)achannel.remoteAddress()).getAddress().getHostAddress();
			String url =  ((InetSocketAddress)achannel.localAddress()).getAddress().getHostAddress() + ":" +
					((InetSocketAddress)achannel.localAddress()).getPort();
			log.info(LoggingConfig.START_TAG);
			//标记用户请求IP
			log.info(LoggingConfig.CLIENT_IP_TAG+ip);
			//标记用户请求URL
			log.info(LoggingConfig.REQUEST_URI_TAG+url);
			//标记用户请求参数
			log.info(LoggingConfig.REQUEST_PARAMS_TAG+"");
			

			if(request != null){
				String requestStr = null;
				requestStr = ((JSONObject)request).toJSONString().replace("token","t o k e n");
				log.debug("Process request:"+requestStr);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 异步处理时记录处理结束
	 * @param log
	 * @param channel
	 * @param result
	 * @param e
	 */
	public void protocolProcessComplete(Logger log,Channel channel, Object result, Throwable e) {
		try{	
			Long end  = System.currentTimeMillis();
			double time = (double)(end-currentThread.get())/1000;
			if(result != null){
				String resultStr = null;
				if(result instanceof JSONObject){
					resultStr = ((JSONObject)result).toJSONString().replace("token","t o k e n");
				}else if(result instanceof RemotingMessage){
					resultStr = new String(((RemotingMessage)result).getBody()).replace("token","t o k e n");
				}else {
					resultStr = result.toString().replace("token","t o k e n");
				}
				log.debug("Process response:"+resultStr);
			}
			
			if(e != null){
				log.info("Process Exception:"+ getStackTrance(e));
			}
			if(time > LoggingConfig.maxTime){
				log.error("--interfacetooslow--");
			}
			log.info("Action RunTime:"+time+"s");
			log.info(LoggingConfig.END_TAG);
		}catch(Exception e1){
			e1.printStackTrace();
		}
	}
	
	/**
	 * 获取异常堆栈
	 * @param e
	 * @return
	 */
	public static String getStackTrance(Throwable e){
		StringBuilder sb = new StringBuilder();
		sb.append(e.getMessage()+"\n");
		StackTraceElement[] st = e.getStackTrace();
		for(StackTraceElement ste:st){
			sb.append(ste.toString()+"\n");
		}
		return sb.toString();
	}


	/**
	 * 同步处理时记录处理开始
	 * @param log
	 * @param request
	 */
	public void protocolProcessBegin(Logger log,HttpServletRequest request) {
		try{
			currentThread.set(System.currentTimeMillis());
			String ip = request.getRemoteHost();
			String url =  request.getContextPath();
			log.info(LoggingConfig.START_TAG);
			//标记用户请求IP
			log.info(LoggingConfig.CLIENT_IP_TAG+ip);
			//标记用户请求URL
			log.info(LoggingConfig.REQUEST_URI_TAG+url);
			//标记用户请求参数
			log.info(LoggingConfig.REQUEST_PARAMS_TAG+"");
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	/**
	 * 同步处理时记录处理结束
	 * @param log
	 * @param request
	 * @param result
	 * @param e
	 */
	public void protocolProcessComplete(Logger log,Object request, Object result, Throwable e) {
		try{
			Long end  = System.currentTimeMillis();
			double time = (double)(end-currentThread.get())/1000;
			
			if(request != null){
				String requestStr = null;
				if(request instanceof JSONObject){
					requestStr = ((JSONObject)request).toJSONString().replace("token","t o k e n");
					
				}else{
					requestStr = request.toString().replace("token","t o k e n");
				}
				log.debug("Process response:"+requestStr);
			}
			
			if(result != null){
				String resultStr = null;
				if(result instanceof JSONObject){
					resultStr = ((JSONObject)result).toJSONString().replace("token","t o k e n");
					
				}else if(result instanceof RemotingMessage){
					resultStr = new String(((RemotingMessage)result).getBody()).replace("token","t o k e n");
				}else{
					resultStr = result.toString().replace("token","t o k e n");
				}
				log.debug("Process response:"+resultStr);
			}
			
			if(e != null){
				log.debug("Process Exception:"+ getStackTrance(e));
			}
			if(time > LoggingConfig.maxTime){
				log.error("--interfacetooslow--");
			}
			log.info("Action RunTime:"+time+"s");
			log.info(LoggingConfig.END_TAG);
		}catch(Exception e1){
			e1.printStackTrace();
		}
	}
}
